<template>
  <div class="update-photo">
    <img :src="img" class="img" ref="imgRef"/>
    <div class="toolbar">
      <div class="cancel">取消</div>
      <div class="confirm" @click="onConfirm">确定</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs/dist/cropper'
import { updateUserAvatar } from '@/api/user.js'
export default {
  name: 'upDatePhoto',
  props: {
    img: [String, Object]
  },
  data () {
    return {
      cropper: null
    }
  },
  created () {},
  mounted () {
    const image = this.$refs.imgRef
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false // 关闭默认背景
    })
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        // console.log(blob)
        const formData = new FormData()
        formData.append('photo', blob)
        // 上传图片
        const res = await updateUserAvatar(formData)
        // 提示成功
        this.$toast.success('操作成功')
        // 修改父组件数据
        this.$emit('update-photo', res.data.data.photo)
        // 关闭弹层
        this.$emit('close')
        // const { data } = updateUserAvatar(FormData)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.update-photo {
  background: rgb(143, 151, 165);
  height: 100%;
}
.toolbar {
  position: fixed;
  bottom: 0;
  display: flex;
  width: 100%;
  color: #fff;
  justify-content: space-between;
  padding: 0 15px 15px;
  box-sizing: border-box;
  font-size: 28px;
}
.img{
    display: block;
    max-width: 100%;
}
</style>